'use strict';

const Controller = require('egg').Controller;
const bcrypt = require('bcryptjs');

class UserController extends Controller {
  // 用户注册
  async register() {
    const { ctx, service } = this;
    
    // 参数验证
    ctx.validate({
      username: { type: 'string', required: true, min: 3, max: 50 },
      email: { type: 'email', required: true },
      password: { type: 'string', required: true, min: 6 },
      nickname: { type: 'string', required: false, max: 50 },
    });

    const { username, email, password, nickname } = ctx.request.body;

    try {
      // 检查用户名和邮箱是否已存在
      const existUser = await service.user.findByUsernameOrEmail(username, email);
      if (existUser) {
        ctx.throw(400, '用户名或邮箱已存在');
      }

      // 密码加密
      const hashedPassword = await bcrypt.hash(password, 10);

      // 创建用户
      const user = await service.user.create({
        username,
        email,
        password: hashedPassword,
        nickname: nickname || username,
      });

      // 生成JWT token
      const token = await service.user.generateToken(user);

      ctx.body = {
        code: 200,
        message: '注册成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            nickname: user.nickname,
            avatar: user.avatar,
          },
          token,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 用户登录
  async login() {
    const { ctx, service } = this;
    
    // 参数验证
    ctx.validate({
      username: { type: 'string', required: true },
      password: { type: 'string', required: true },
    });

    const { username, password } = ctx.request.body;

    try {
      // 查找用户
      const user = await service.user.findByUsernameOrEmail(username, username);
      if (!user) {
        ctx.throw(400, '用户不存在');
      }

      // 验证密码
      const isValidPassword = await bcrypt.compare(password, user.password);
      if (!isValidPassword) {
        ctx.throw(400, '密码错误');
      }

      // 更新最后登录时间
      await service.user.updateLastLogin(user.id);

      // 生成JWT token
      const token = await service.user.generateToken(user);

      ctx.body = {
        code: 200,
        message: '登录成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            nickname: user.nickname,
            avatar: user.avatar,
          },
          token,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取用户信息
  async profile() {
    const { ctx, service } = this;

    // 检查用户认证状态
    const userId = ctx.getCurrentUserId();

    try {
      const user = await service.user.findById(userId);
      if (!user) {
        ctx.throw(404, '用户不存在');
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
          nickname: user.nickname,
          avatar: user.avatar,
          gender: user.gender,
          birthday: user.birthday,
          height: user.height,
          weight: user.weight,
          bio: user.bio,
          created_at: user.created_at,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新用户信息
  async updateProfile() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    // 参数验证
    ctx.validate({
      nickname: { type: 'string', required: false, max: 50 },
      gender: { type: 'enum', values: ['male', 'female', 'other'], required: false },
      birthday: { type: 'date', required: false },
      height: { type: 'int', required: false, min: 50, max: 300 },
      weight: { type: 'int', required: false, min: 20, max: 500 },
      bio: { type: 'string', required: false, max: 500 },
    });

    try {
      const updateData = ctx.request.body;
      await service.user.updateById(userId, updateData);

      ctx.body = {
        code: 200,
        message: '更新成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 修改密码
  async changePassword() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    // 参数验证
    ctx.validate({
      oldPassword: { type: 'string', required: true },
      newPassword: { type: 'string', required: true, min: 6 },
    });

    const { oldPassword, newPassword } = ctx.request.body;

    try {
      const user = await service.user.findById(userId);
      
      // 验证旧密码
      const isValidPassword = await bcrypt.compare(oldPassword, user.password);
      if (!isValidPassword) {
        ctx.throw(400, '原密码错误');
      }

      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);
      
      // 更新密码
      await service.user.updateById(userId, { password: hashedPassword });

      ctx.body = {
        code: 200,
        message: '密码修改成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 上传头像
  async uploadAvatar() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      const file = ctx.request.files[0];
      if (!file) {
        ctx.throw(400, '请选择文件');
      }

      // 上传文件
      const avatarUrl = await service.upload.uploadImage(file, 'avatar');
      
      // 更新用户头像
      await service.user.updateById(userId, { avatar: avatarUrl });

      ctx.body = {
        code: 200,
        message: '头像上传成功',
        data: {
          avatar: avatarUrl,
        },
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取用户偏好
  async getPreferences() {
    const { ctx, service } = this;

    // 检查用户认证状态


    const userId = ctx.state.user?.id || 1;

    try {
      const preferences = await service.user.getPreferences(userId);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: preferences,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新用户偏好
  async updatePreferences() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;
    const preferences = ctx.request.body;

    try {
      // 先清除现有偏好
      await ctx.model.UserPreference.destroy({
        where: { user_id: userId },
      });

      // 批量创建新偏好
      const preferenceData = preferences.map(pref => ({
        ...pref,
        user_id: userId,
      }));

      await ctx.model.UserPreference.bulkCreate(preferenceData);

      ctx.body = {
        code: 200,
        message: '偏好设置保存成功',
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取用户统计
  async getStats() {
    const { ctx, service } = this;
    const userId = ctx.state.user?.id || 1;

    try {
      const stats = await service.user.getStats(userId);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: stats,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取穿搭提醒设置
  async getReminders() {
    const { ctx, service } = this;



    try {
      const reminders = await service.user.getReminders(ctx.state.user?.id || 1);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: reminders,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 更新穿搭提醒设置
  async updateReminders() {
    const { ctx, service } = this;



    try {
      const reminders = await service.user.updateReminders(
        ctx.state.user?.id || 1,
        ctx.request.body
      );

      ctx.body = {
        code: 200,
        message: '更新成功',
        data: reminders,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }

  // 获取购买建议
  async getBuyingSuggestions() {
    const { ctx, service } = this;



    try {
      const suggestions = await service.user.getBuyingSuggestions(ctx.state.user?.id || 1);

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: suggestions,
      };
    } catch (error) {
      ctx.throw(500, error.message);
    }
  }
}

module.exports = UserController;
